<template>
  <div class="user-container">
    <Header title='机构认证' :titleDes='crumb'></Header>
    <div class="body">
      <Steps style="width:80%; margin:0 auto" :current="formItem.authorState">
        <Step title="提交资料" content=""></Step>
        <Step title="审核中" content=""></Step>
        <Step title="认证成功" content=""></Step>
      </Steps>

      <div v-if="(formItem.authorState==3 && formItem.failReason)" class="error">
        审核意见:{{formItem.failReason}}
      </div>

      <Card style="margin-top:10px" :bordered="false">
        <p class="base" slot="title">基本资料</p>
        <Form ref="baseform" class="baseform" :model="formItem" :rules="ruleValidate" :label-width="140">
          <FormItem label="机构名称" prop="ylyName">
            <Input v-if="disabled" v-model="formItem.ylyName" placeholder="请输入机构名称"></Input>
            <span v-else>{{formItem.ylyName}}</span>
          </FormItem>
          <FormItem label="机构地址" prop="detailAddress">
            <div v-if="disabled">
              <Select v-model="formItem.provinceId" label-in-value style="width:32%;margin-right:2%" @on-change="provinceChange" placeholder='请选择省份'>
                <Option v-for="item in provinces" :key="item.id" :value="item.id">{{ item.name }}</Option>
              </Select>
              <Select v-model="formItem.cityId" label-in-value style="width:32%;margin-right:2%" @on-change="cityChange" placeholder='请选择城市'>
                <Option v-for="item in cities" :key="item.id" :value="item.id">{{ item.name }}</Option>
              </Select>
              <Select v-model="formItem.districtId" label-in-value style="width:32%" @on-change="districtChange" placeholder='请选择区域'>
                <Option v-for="item in districts" :key="item.id" :value="item.id">{{ item.name }}</Option>
              </Select>
              <Input style="margin-top:5px" v-model="formItem.detailAddress" type="textarea" :rows="4" placeholder="请输入具体地址"></Input>
            </div>
            <span v-else>{{formItem.provinceName}}省{{formItem.cityName}}市{{formItem.districtName}}区{{formItem.detailAddress}}</span>
          </FormItem>
          <FormItem label="占地面积" prop="ylySquare">
            <Input v-if="disabled" v-model="formItem.ylySquare" placeholder="请输入占地面积"></Input>
            <span v-else>{{formItem.ylySquare}}</span>
          </FormItem>
          <FormItem label="机构类型" prop="ylyType">
            <Select v-if="disabled" v-model="formItem.ylyType" placeholder='请选择机构类型'>
              <Option v-for="item in lylTypes" :value="item.key" :key="item.key">{{ item.value }}</Option>
            </Select>
            <span v-else>{{formItem.ylyType}}</span>
          </FormItem>
          <FormItem label="床位数量" prop="bedNum">
            <Input type="number" v-if="disabled" v-model="formItem.bedNum" placeholder="请输入床位数量"></Input>
            <span v-else>{{formItem.bedNum}}</span>
          </FormItem>
          <FormItem label="受助对象" prop="guestType">
            <Checkbox-group v-if="disabled" v-model="formItem.guestTypedesc">
              <Checkbox v-for="item in guestTypes" v-bind:key="item.index" :label="item.key">{{ item.value }}</Checkbox>
            </Checkbox-group>
            <span v-else>{{formItem.guestType}}</span>
          </FormItem>
          <FormItem label="员工人数" prop="employeeNum">
            <Input v-if="disabled" v-model="formItem.employeeNum" placeholder="请输入床位数量"></Input>
            <span v-else>{{formItem.employeeNum}}</span>
          </FormItem>
          <FormItem label="收费区间" prop="costMax">
            <Row>
              <Col span="6">
              <Input v-if="disabled" v-model="formItem.costMin" placeholder=""></Input>
              <span v-else>{{formItem.costMin}}</span>
              </Col>
              <Col span="2" style="text-align: center">~</Col>
              <Col span="6">
              <Input v-if="disabled" v-model="formItem.costMax" placeholder=""></Input>
              <span v-else>{{formItem.costMax}}</span>
              </Col>
              <Col span="2" style="text-align: center">元</Col>
            </Row>
          </FormItem>
        </Form>
      </Card>

      <Card :bordered="false">
        <p class="base" slot="title">认证资料</p>
        <Form ref="certform" class="baseform" :model="formItem" :rules="ruleValidate" :label-width="140">
          <FormItem label="统一社会信用代码" prop="creditCode">
            <Input v-if="disabled" v-model="formItem.creditCode" placeholder="请输入统一社会信用代码"></Input>
            <span v-else>{{formItem.creditCode}}</span>
          </FormItem>
          <FormItem label="企业营业执照" prop="licenseUrl">
            <Upload ref="license" v-show="disabled&&formItem.licenseUrl===''" style="width: 300px;height:200px;" :show-upload-list="true" :on-success="handleSuccess" :format="['jpg','jpeg','png']" :max-size="2048" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :before-upload="creditCodeBeforeUpload" type="drag" action=''>
              <div style="width: 300px;height:200px;line-height: 200px;">
                <Icon type="ios-cloud-upload-outline" size='30'></Icon>
              </div>
            </Upload>
            <div v-show="!(formItem.licenseUrl==='')" class="upload-list">
              <img style="width:100%;height:100%" :src="formItem.licenseUrl"></img>
              <Row class="upload-list-cover">
                <Col span="12">
                <Icon type="ios-eye-outline" color='#fff' size='30' @click.native="handleView(formItem.licenseUrl)"></Icon>
                </Col>
                <Col span="12" v-show="disabled">
                <Icon type="ios-trash-outline" color='#fff' size='30' @click.native="handleRemove('licenseUrl')"></Icon>
                </Col>
              </Row>
            </div>
          </FormItem>
          <FormItem label="税务登记复印件" prop="taxUrl">
            <Upload ref="tax" v-show="disabled&&formItem.taxUrl===''" style="width: 300px;height:200px;" :show-upload-list="true" :on-success="handleSuccess" :format="['jpg','jpeg','png']" :max-size="2048" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :before-upload="taxBeforeUpload" type="drag" action=''>
              <div style="width: 300px;height:200px;line-height: 200px;">
                <Icon type="ios-cloud-upload-outline" size='30'></Icon>
              </div>
            </Upload>
            <div v-show="!(formItem.taxUrl==='')" class="upload-list">
              <img style="width:100%;height:100%" :src="formItem.taxUrl"></img>
              <Row class="upload-list-cover">
                <Col span="12">
                <Icon type="ios-eye-outline" color='#fff' size='30' @click.native="handleView(formItem.taxUrl)"></Icon>
                </Col>
                <Col span="12" v-show="disabled">
                <Icon type="ios-trash-outline" color='#fff' size='30' @click.native="handleRemove('taxUrl')"></Icon>
                </Col>
              </Row>
            </div>
          </FormItem>
          <FormItem label="法人姓名" prop="legalName">
            <Input v-if="disabled" v-model="formItem.legalName" placeholder="请输入法人姓名"></Input>
            <span v-else>{{formItem.legalName}}</span>
          </FormItem>
          <FormItem label="法人身份证号码" prop="legalId">
            <Input v-if="disabled" v-model="formItem.legalId" placeholder="请输入法人身份证号码"></Input>
            <span v-else>{{formItem.legalId}}</span>
          </FormItem>
          <FormItem label="法人身份证" prop="">
            <Row :gutter='12'>
              <Col span="8">
              <Upload ref="legalIdPositive" v-show="disabled&&formItem.legalIdPositiveUrl===''" style="width: 200px;height:200px;" :show-upload-list="true" :on-success="handleSuccess" :format="['jpg','jpeg','png']" :max-size="2048" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :before-upload="legalIdPositiveBeforeUpload" type="drag" action=''>
                <div style="width: 200px;height:200px;line-height: 200px;">
                  <Icon type="ios-cloud-upload-outline" size='30'></Icon>
                </div>
              </Upload>
              <div v-show="!(formItem.legalIdPositiveUrl==='')" class="upload-list">
                <img style="width:100%;height:100%" :src="formItem.legalIdPositiveUrl"></img>
                <Row class="upload-list-cover">
                  <Col span="12">
                  <Icon type="ios-eye-outline" color='#fff' size='30' @click.native="handleView(formItem.legalIdPositiveUrl)"></Icon>
                  </Col>
                  <Col span="12" v-show="disabled">
                  <Icon type="ios-trash-outline" color='#fff' size='30' @click.native="handleRemove('legalIdPositiveUrl')"></Icon>
                  </Col>
                </Row>
              </div>
              </Col>
              <Col span="8">
              <Upload ref="legalIdBack" v-show="disabled&&formItem.legalIdBackUrl===''" style="width: 200px;height:200px;" :show-upload-list="true" :on-success="handleSuccess" :format="['jpg','jpeg','png']" :max-size="2048" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :before-upload="legalIdBackBeforeUpload" type="drag" action=''>
                <div style="width: 200px;height:200px;line-height: 200px;">
                  <Icon type="ios-cloud-upload-outline" size='30'></Icon>
                </div>
              </Upload>
              <div v-show="!(formItem.legalIdBackUrl==='')" class="upload-list">
                <img style="width:100%;height:100%" :src="formItem.legalIdBackUrl"></img>
                <Row class="upload-list-cover">
                  <Col span="12">
                  <Icon type="ios-eye-outline" color='#fff' size='30' @click.native="handleView(formItem.legalIdBackUrl)"></Icon>
                  </Col>
                  <Col span="12" v-show="disabled">
                  <Icon type="ios-trash-outline" color='#fff' size='30' @click.native="handleRemove('legalIdBackUrl')"></Icon>
                  </Col>
                </Row>
              </div>
              </Col>
            </Row>
          </FormItem>
        </Form>
      </Card>
      <Row style="text-align:center;margin-top:10px;">
        <Button v-if="disabled" style="margin-right:2rem" @click="save"> 保存资料</Button>
        <Button v-if="disabled" type="success" @click="submit"> 提交资料</Button>
      </Row>
      <Modal title="查看图片" v-model="visible">
        <img :src="imgName" v-if="visible" style="width: 100%">
      </Modal>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import Header from '../components/Header'
import Footer from '../components/Footer'
import { Component, Vue, Watch } from 'vue-property-decorator'
import ajax from '../lib/ajax'
import ajaxfile from '../lib/ajaxfile'

class Req {
  ylyName = ''
  provinceName = ''
  cityName = ''
  districtName = ''
  detailAddress = ''
  fullAddress = ''
  ylySquare = ''
  ylyType = ''
  ylyTypeName = ''
  employeeNum = 0
  guestTypedesc = []
  guestType = ''
  guestTypeName = ''
  bedNum = 0
  costMax = 0
  costMin = 0
  creditCode = ''
  licenseUrl = ''
  legalId = ''
  legalIdPositiveUrl = ''
  legalIdBackUrl = ''
  taxUrl = ''
}

@Component({
  components: {
    Header,
    Footer
  }
})

export default class Home extends Vue {
  disabled = false
  crumb = [{ title: '个人中心', link: '/Home' }, { title: '机构认证', link: '/User?id=3' }, { title: '填写资料', link: '/User/Validate' }]
  provinces = []
  cities = []
  districts = []
  visible = false
  formItem = new Req()
  lylTypes = [{ key: 1, value: '民营' }, { key: 2, value: '公办(建)' }, { key: 3, value: '公办民营' }, { key: 4, value: '公助民办' }, { key: 5, value: '公建民营' }, { key: 6, value: '公办公营' }, { key: 7, value: '社会团体' }, { key: 8, value: '其他' }]

  guestTypes = [{ key: 1, value: '自理' }, { key: 2, value: '半护理' }, { key: 3, value: '全护' }, { key: 4, value: '特护' }, { key: 5, value: '专护' }]

  save() {
    // this.formItem.fullAddress = this.formItem.provinceName + this.formItem.cityName + this.formItem.districtName
    sessionStorage.setItem('institudeInfo', JSON.stringify(this.formItem))
    this.$Message.success('已保存草稿')
  }

  submit() {
    // this.formItem.fullAddress = this.formItem.provinceName + this.formItem.cityName + this.formItem.districtName
    this.$Modal.confirm({
      title: '确认',
      content: '确认要提交资料信息吗',
      onOk: () => {
        if (this.formItem.guestTypedesc.length === 0) {
          this.$Message.error('至少选择一个受助对象')
          return
        }
        this.formItem.guestType = ''
        for (let i = 0; i < this.formItem.guestTypedesc.length; i++) {
          if (i === this.formItem.guestTypedesc.length - 1) {
            this.formItem.guestType = this.formItem.guestType + this.formItem.guestTypedesc[i]
          } else {
            this.formItem.guestType = this.formItem.guestType + this.formItem.guestTypedesc[i] + ','
          }
        }
        ajax.post('author', this.formItem).then(result => {
          if (result.data.code === 200) {
            ajax.post('authorState').then(r => {
              this.$store.commit('session/setAuthorStates', r.data.data)
              this.$Message.success('恭喜你 提交成功')
              this.$router.push('../User?id=3')
            })
          }
        })
      },
      onCancel: () => {
        this.$Message.info('取消成功')
      }
    })
  }

  get userInfo() {
    return this.$store.getters['session/user']
  }

  @Watch('$route')
  onChildChanged(newVal, oldVal) {
    if (oldVal.path === '/User/Validate') {
    } else if (newVal.path === '/User/Validate') {
      console.log('%c%s', 'color:orange', 'validate oldVal.path' + oldVal.path)
      console.log('%c%s', 'color:orange', 'validate newVal.path' + newVal.path)
      this.fetchData()
    }
  }

  fetchData() {
    console.log('%c%s', 'color:red', 'validate fetchData')
    ajax.post('getAuthorData').then(result => {
      console.log('getAuthorData', result.data.data)
      if (result.data.data) {
        this.formItem = result.data.data
        if (this.formItem.authorState === 3) {
          this.disabled = true
          ajax.get('getSingleAreaList?parentId=0').then(result => {
            this.provinces = result.data.data
          })
        } else {
          this.disabled = false
        }
      } else {
        this.disabled = true
        ajax.get('getSingleAreaList?parentId=0').then(result => {
          this.provinces = result.data.data
        })

        if (sessionStorage.getItem('institudeInfo')) {
          this.formItem = JSON.parse(sessionStorage.getItem('institudeInfo'))
        }
      }
    })
  }

  created() {
    console.log('%c%s', 'color:blue', 'validate created 创建完毕状态')
    this.fetchData()
  }

  beforeMount() {
    console.log('%c%s', 'color:blue', 'validate beforeMount 挂载前状态')
  }

  beforeCreate() {
    console.log('%c%s', 'color:blue', 'validate beforeCreate 创建前状态')
  }

  mounted() {
    console.log('%c%s', 'color:blue', 'validate mounted 挂载结束状态')
  }

  // beforeUpdate() {
  //   console.log('%c%s', 'color:blue', 'validate beforeUpdate 更新前状态')
  // }

  // updated() {
  //   console.log('%c%s', 'color:blue', 'validate updated 更新完成状态')
  // }

  beforeDestroy() {
    console.log('%c%s', 'color:blue', 'validate beforeDestroy 销毁前状态')
  }

  destroyed() {
    console.log('%c%s', 'color:blue', 'validate destroyed 销毁完成状态')
  }

  provinceChange(province) {
    this.formItem.provinceId = province.value
    this.formItem.provinceName = province.label
    if (province && province.value > 0) {
      ajax.get('getSingleAreaList?parentId=' + province.value).then(result => {
        this.cities = result.data.data
      })
    } else {
      this.cities = []
      this.districts = []
    }
  }

  cityChange(city) {
    this.formItem.cityId = city.value
    this.formItem.cityName = city.label
    if (city && city.value > 0) {
      ajax.get('getSingleAreaList?parentId=' + city.value).then(result => {
        this.districts = result.data.data
      })
    } else {
      this.districts = []
    }
  }

  districtChange(district) {
    this.formItem.districtId = district.value
    this.formItem.districtName = district.label
    if (district && district.value > 0) {
      ajax.get('getSingleAreaList?parentId=' + district.value).then(result => {
        this.districts = result.data.data
      })
    } else {
      this.districts = []
    }
  }

  creditCodeBeforeUpload(file) {
    const uploadData = new FormData()
    uploadData.append('file', file)
    // uploadData.append('token', this.$store.state.session.token)
    console.log('%c%s', 'color:red', 'creditCodeBeforeUpload token==>' + this.$store.state.session.token)
    ajaxfile.post('uploadFile', uploadData).then(result => {
      if (result.data.code === 200) {
        this.formItem.licenseUrl = result.data.data
      }
    })

    return false
  }

  UploadLicense() {
    this.$refs.license.$el.dispatchEvent(new MouseEvent('click'))
  }

  legalIdBackBeforeUpload(file) {
    const uploadData = new FormData()
    uploadData.append('file', file)
    ajaxfile.post('uploadFile', uploadData).then(result => {
      if (result.data.code === 200) {
        this.formItem.legalIdBackUrl = result.data.data
      }
    })

    return false
  }

  UploadlegalIdBack() {
    this.$refs.legalIdBack.$el.dispatchEvent(new MouseEvent('click'))
  }

  legalIdPositiveBeforeUpload(file) {
    const uploadData = new FormData()
    uploadData.append('file', file)
    ajaxfile.post('uploadFile', uploadData).then(result => {
      if (result.data.code === 200) {
        this.formItem.legalIdPositiveUrl = result.data.data
      }
    })

    return false
  }

  UploadlegalIdPositive() {
    this.$refs.legalIdPositive.$el.dispatchEvent(new MouseEvent('click'))
  }

  taxBeforeUpload(file) {
    const uploadData = new FormData()
    uploadData.append('file', file)
    ajaxfile.post('uploadFile', uploadData).then(result => {
      if (result.data.code === 200) {
        this.formItem.taxUrl = result.data.data
      }
    })

    return false
  }

  UploadTax() {
    this.$refs.tax.$el.dispatchEvent(new MouseEvent('click'))
  }

  handleView(name) {
    this.imgName = name
    this.visible = true
  }

  handleRemove(file) {
    // 从 upload 实例删除数据
    switch (file) {
      case 'licenseUrl':
        this.formItem.licenseUrl = ''
        break
      case 'legalIdPositiveUrl':
        this.formItem.legalIdPositiveUrl = ''
        break
      case 'legalIdBackUrl':
        this.formItem.legalIdBackUrl = ''
        break
      case 'taxUrl':
        this.formItem.taxUrl = ''
        break
    }
  }

  handleSuccess(res, file) {
    // 因为上传过程为实例，这里模拟添加 url
    alert(file.url)
    file.url = 'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar'
    file.name = '7eb99afb9d5f317c912f08b5212fd69a'
  }

  handleFormatError(file) {
    this.$Notice.warning({
      title: '文件格式不正确',
      desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
    })
  }

  handleMaxSize(file) {
    this.$Notice.warning({
      title: '超出文件大小限制',
      desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
    })
  }

  ruleValidate = {
    ylyName: [
      { required: true, message: '机构名称不能为空', trigger: 'blur' }
    ],
    ylyType: [
      { required: true, type: 'number', message: '机构类型不能为空', trigger: 'change' }
    ],
    ylySquare: [
      { required: true, message: '占地面积不能为空', trigger: 'blur' }
    ],
    // guestType: [
    //   { required: true, type: 'array', min: 1, message: '至少选择一个受助对象', trigger: 'change' }
    // ],
    detailAddress: [
      { required: true, message: '机构地址不能为空', trigger: 'blur' }
    ],
    interest: [
      { required: true, type: 'array', min: 1, message: '至少选择一个爱好', trigger: 'change' },
      { type: 'array', max: 2, message: '最多选择两个爱好', trigger: 'change' }
    ],
    bedNum: [
      { required: true, message: '床位数量不能为空', trigger: 'blur' }
    ],
    employeeNum: [
      { required: true, message: '员工数量不能为空', trigger: 'blur' }
    ],
    time: [
      { required: true, type: 'date', message: '请选择时间', trigger: 'change' }
    ],
    costMax: [
      { required: true, message: '请输入收费开始区间', trigger: 'blur' }
    ],
    feeTo: [
      { required: true, message: '请输入收费结束区间', trigger: 'blur' }
    ],
    desc: [
      { required: true, message: '请输入个人介绍', trigger: 'blur' },
      { type: 'string', min: 20, message: '介绍不能少于20字', trigger: 'blur' }
    ],
    creditCode: [
      { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
    ],
    legalName: [
      { required: true, message: '请输入法人姓名', trigger: 'blur' }
    ],
    licenseUrl: [
      { required: true, message: '请输入营业执照图片', trigger: 'blur' }
    ],
    legalId: [
      { required: true, message: '请输入法人身份证号', trigger: 'blur' }
    ],
    legalIdPositiveUrl: [
      { required: true, message: '请输入法人身份证正面地址', trigger: 'blur' }
    ],
    legalIdBackUrl: [
      { required: true, message: '请输入法人身份证反面地址', trigger: 'blur' }
    ],
    taxUrl: [
      { required: true, message: '请输入税务登记证地址', trigger: 'blur' }
    ]
  }
}

</script>
<style scoped>
.body {
  text-align: left;
  padding: 5rem 25% 4rem 25%;
  margin-bottom: 20px;
}
.baseform {
  font-size: 1.2rem;
  width: 90%;
  margin: 0 auto;
}

.error {
  width: 80%;
  margin: 20px auto;
  padding: 10px;
  background: #fff9f9;
  border: solid 1px #ff2e2e;
  border-radius: 4px;
  color: #ff2e2e;
  font-weight: bold;
  font-size: 12px;
}
.validate {
  width: 200px;
  height: 300px;
}

.level {
  width: 200px;
  height: 300px;
}
.center {
  text-align: center;
}
.base {
  margin-top: 1rem;
}
span {
  color: #b1b1b1;
}
.upload-list {
  width: 200px;
  height: 200px;
  line-height: 200px;
  cursor: pointer;
}
.upload-list-cover {
  width: 200px;
  height: 200px;
  text-align: center;
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.upload-list:hover .upload-list-cover {
  display: block;
}
</style>
